package cn.fenqing168.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Service
public class PaymentService {

    /**
     * 成功的方法
     * @return
     */
    public String paymentInfoOk(Long id){
        return "线程池： " + Thread.currentThread().getName() + "  paymentInfoOk,id" + id;
    }

    /**
     * 有可能会失败的方法
     * @param id
     * @return
     */
    @SneakyThrows
    @HystrixCommand(
            //出异常执行哪个方法（必须在同一个类）
            fallbackMethod = "paymentInfoTimeOutFallBack",
            commandProperties = {
                    // 修改超时时间，测试超时时间大于线程睡眠时间，是否会触发fallback
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5100")
            }
    )
    public String paymentInfoTimeOut(Long id){
        //异常的情况,测试是否也会进fallback
        // int num = 10 / 0;
        // 线程睡眠3秒钟，对应的是模拟触发服务降级的条件之一：“超时”
        int timeout = 5;
        TimeUnit.SECONDS.sleep(timeout);
        return "线程池： " + Thread.currentThread().getName() + "  paymentInfoTimeOut,id" + id + "  耗时 " + timeout;
    }

    @SneakyThrows
    public String paymentInfoTimeOutFallBack(Long id){
        return "进入fallback：线程池： " + Thread.currentThread().getName() + "  paymentInfoTimeOutFallBack,id" + id;
    }

    //服务熔断

    /**
     * 真正的业务方法
     * @param id
     * @return
     */
    @HystrixCommand(
            fallbackMethod = "paymentCircuitBreakerFallBack",
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//是否开启断路器
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间范围
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")//失败率达到多少后熔断
            }
    )
    public String paymentCircutBreaker(Long id){
        if(id < 0){
            //给出一个能出异常的情况
            throw new RuntimeException("id不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t调用成功，流水号" + serialNumber;
    }

    /**
     * 服务熔断后，触发的fallback
     * @param id
     * @return
     */
    public String paymentCircuitBreakerFallBack(Long id){
        return "id 不能为负数，请稍后再试，此乃fallback";
    }

}
